package com.utils;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class JWTUtils {
    private static final String SING = "15b51fce28cc6c8d04c98b223ce84e0b";

    /**
     * 生成Token  header.payload.sign
     */
    public static String getToken(String content) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7); //默认7天过期
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("content", EncryptUtil.encryptDES(content,SING));
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     *  验证token的合法性
     */
    public static boolean verify(String token){
        try{
            JWT.require(Algorithm.HMAC256(SING)).build().verify(token);  //这一行代码就可以起到验证的作用，因为在验证不匹配时它自动会抛出异常
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 获取token的信息方法
     */
    public static String getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        String content = EncryptUtil.decryptDES(verify.getClaim("content").as(String.class), SING);
        return content;
    }

    public static void main(String[] args) {

        Map<String,Object> maps = new HashMap<>();
        maps.put("userId",1);
        maps.put("data","lisi");
        String token1 = JWTUtils.getToken(JSON.toJSONString(maps));
        String encryptAES = EncryptUtil.encryptDES(JSON.toJSONString(maps), SING);
        System.out.println(encryptAES);
        System.out.println(EncryptUtil.decryptDES(encryptAES, SING));


        System.out.println(token1);
        System.out.println(JWTUtils.verify(token1));
        System.out.println(JWTUtils.getTokenInfo(token1));
    }
}
